package com.wswy.wzcx.utils;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.NonNull;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import com.blankj.utilcode.util.AppUtils;
import com.che.libcommon.utils.ToastUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.StatusUtil;
import com.liulishuo.okdownload.StatusUtil.Status;
import com.wswy.wzcx.AppContext;
import com.wswy.wzcx.utils.DownloadNotificationListener.DownloadCallback;
import java.io.File;
import timber.log.Timber;

public class DownloadUtils {

  private static BroadcastReceiver downloadReceiver;


  public static void downloadApk(String url,String title){

    try {

      Context context = AppContext.getContext();

      if (downloadReceiver != null){
        context.unregisterReceiver(downloadReceiver);
      }

      DownloadTask task = new DownloadTask.Builder(url, context.getExternalFilesDir("download"))
          .setPassIfAlreadyCompleted(true)
          .build();

      Timber.e("----"+ StatusUtil.getStatus(task));

      DownloadNotificationListener listener = new DownloadNotificationListener(context);
      listener.attachTaskEndRunnable(new DownloadCallback() {
        @Override
        public void onEnd(boolean complete, File file) {

          try {
            if (downloadReceiver != null){
              AppContext.getContext().unregisterReceiver(downloadReceiver);
            }
            downloadReceiver = null;


            if (complete && file != null){
              //下载完成
              AppUtils.installApp(file);

            }

          } catch (Exception e) {
            e.printStackTrace();
          }

        }
      });

      IntentFilter filter = new IntentFilter(DownloadReceiver.CANCEL);
      filter.addAction(DownloadReceiver.CONTENT);

      downloadReceiver = new DownloadReceiver(task);
      context.registerReceiver(downloadReceiver, filter);



      final Intent intent = new Intent(context,DownloadReceiver.class);
      intent.setAction(DownloadReceiver.CANCEL);

      final PendingIntent cancelPendingIntent = PendingIntent.getBroadcast(context, 0, intent,
          PendingIntent.FLAG_UPDATE_CURRENT);

      listener.setAction(new NotificationCompat.Action(0, "取消", cancelPendingIntent));


      final Intent clickIntent = new Intent(context,DownloadReceiver.class);
      clickIntent.setAction(DownloadReceiver.CONTENT);
      final PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, clickIntent,
          PendingIntent.FLAG_UPDATE_CURRENT);
      listener.initNotification(title,pendingIntent);

      DownloadTask.enqueue(new DownloadTask[]{task},
          listener);

      ToastUtils.showText("开始下载");

    }catch (Throwable e){
      e.printStackTrace();
    }
  }

  static class DownloadReceiver extends BroadcastReceiver {
    static final String CANCEL = "DownloadReceiver.cancelOkdownload";

    static final String CONTENT = "DownloadReceiver.content.click";

    private DownloadTask task;

    DownloadReceiver(@NonNull DownloadTask task) {
      this.task = task;
    }

    @Override public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();

      if (TextUtils.equals(action,CANCEL)){
        this.task.cancel();
      }else if (TextUtils.equals(action,CONTENT)){

        try {
          Status status = StatusUtil.getStatus(task);
          if (status == Status.COMPLETED){
            //完成，拉起安装
            AppUtils.installApp(task.getFile());
          }

        }catch (Throwable throwable){

        }

      }

    }
  }
}
